<template>
  <div class="container">
    <a-card class="custom-card" title="">
      <a-table
        row-key="id"
        :loading="loading"
        :pagination="false"
        :data="renderData"
        :bordered="{ wrapper: true, cell: true }"
        :scroll="tableScroll"
        column-resizable
      >
        <template #columns>
          <a-table-column title="序号" data-index="numbers" align="center" :width="80"/>
          <a-table-column title="备份文件名称" data-index="name" align="center" :ellipsis="true" :tooltip="true" :width="200"/>
          <a-table-column title="卷数" data-index="part" align="center" :width="100"/>
          <a-table-column title="压缩" data-index="compress" align="center" :width="100"/>
          <a-table-column title="数据大小" data-index="size" align="center" :width="100"/>
          <a-table-column title="备份时间" data-index="mtime" align="center" :width="160"/>
          <a-table-column title="操作" data-index="operations" align="center" fixed="right" :width="240">
            <template #cell="{ record }">
              <a-space>
                <a-button type="primary" status="warning" size="small" @click="download(record)"><template #icon><icon-to-bottom /></template>下载</a-button>
                <a-popconfirm content="确定要还原这条备份数据吗？" type="warning" position="br" @ok="doImport(record)">
                  <a-button type="primary" :class="`btn--${record.name}`" size="small">
                    <template #icon><icon-arrow-left /></template>还原
                  </a-button>
                </a-popconfirm>
                <a-popconfirm content="确定要删除这条备份数据吗？" type="warning" position="br" @ok="del(record)">
                  <a-button type="primary" status="danger" size="small"><template #icon><icon-delete /></template>删除</a-button>
                </a-popconfirm>
              </a-space>
            </template>
          </a-table-column>
        </template>
      </a-table>
    </a-card>
  </div>
</template>

<script lang="ts" setup>
  import { ref } from 'vue';
  import { useI18n } from 'vue-i18n';
  // import { Message } from '@arco-design/web-vue';

  import useLoading from '@/hooks/loading';
  import { downloadFile } from '@/utils';
  import screenHeight from '@/utils/screen-height';
  // import checkPermission from '@/utils/permission';
  import { ImportState, apiImportList, apiImport, apiDel } from '@/api/database';

  const { loading, setLoading } = useLoading(true);
  const { t } = useI18n();
  const height = screenHeight(215);
  const renderData = ref<ImportState[]>([]);
  const tableScroll = ref({
    x: '100%',
    y: height,
  });

  // 列表
  const fetchData = async (params?: any) => {
    setLoading(true);
    try {
      const { data } = await apiImportList(params);
      renderData.value = data.data;
    } catch (err) {
      // you can report use errorHandler or other
    } finally {
      setLoading(false);
    }
  };
  // 还原
  const doImport = async (row: ImportState) => {
    setLoading(true);
    await apiImport({
      time: row.time,
      filepath: row.filepath,
    }).then(res => {
      restore(res.data, row);
    }).catch(() => {
      setLoading(false);
    });

    window.onbeforeunload = function () {
      return '正在还原数据库，请不要关闭！';
    };
  };
  // 删除
  const del = async (row: ImportState) => {
    setLoading(true);
    try {
      await apiDel({
        time: row.time,
        filepath: row.filepath,
      });
    } catch (err) {
      setLoading(false);
    } finally {
      fetchData();
      setLoading(false);
    }
  };
  // 下载
  const download = async (row: ImportState) => {
    downloadFile(row.full_filepath);
  };

  // 恢复
  const restore = async (data: any, row: ImportState) => {
    if (data.status === -1) {
      // 初始化
      await apiImport({
        part: data.part,
        start: data.start,
        time: data.time,
      }).then(res2 => {
        restore(res2.data, row);
      }).catch(() => {
        setLoading(false);
      });
    } else if (data.status === 1) {
      // 开始恢复
      setTimeout(() => {
        setLoading(false);
        document.getElementsByClassName(`btn--${row.name}`)[0].innerHTML = data.info;
      }, 2000);
      if (data.part) {
        await apiImport({
          part: data.part,
          start: data.start,
        }).then(res2 => {
          restore(res2.data, row);
        }).catch(() => {
          setLoading(false);
        });
      } else {
        window.onbeforeunload = function () {
          return null;
        }
      }
    }
  };

  fetchData();
</script>

<script lang="ts">
  export default {
    name: 'DatabaseImport',
  };
</script>

<style scoped lang="less">
  :deep(.arco-table-th) {
    &:last-child {
      .arco-table-th-item-title {
        margin-left: 16px;
      }
    }
  }
</style>
